<template>
  <v-container style="max-width: 1900px; min-height: 400px;">
    <h1 style="color: #4a90e2;font-size: 50px">批量设备评估</h1>

    <ExcelUpload @file-parsed="handleParsedData" @parse-error="handleParseError" />

    <v-btn
        color="primary"
        @click="startBatchEvaluation"
        :disabled="parsedDevices.length === 0 || isLoading"
        :loading="isLoading"
        class="my-4"
    >
      开始批量评估 ({{ parsedDevices.length }} 台)
    </v-btn>

    <EvaluationResultsSummary
        :results="evaluatedDevices"
        :is-loading="isLoading && !evaluatedDevices.length"
        :progress="evaluationProgress"
        @view-details="showDeviceDetails"
        @generate-reports="handleGenerateBatchReports"
        @generate-single-report="handleGenerateSingleReport"
        class="mt-4"
    />

    <EvaluationDetailDialog
        v-model="showDetailDialog"
        :device-data="selectedDeviceForDetail"
        :secondary-indicators="secondaryIndicators"
        :primary-indicator-weights="primaryIndicatorWeights"
        @generate-report="handleGenerateSingleReport"
    />

    <v-snackbar v-model="snackbar.show" :color="snackbar.color" timeout="4000">
      {{ snackbar.text }}
      <template v-slot:actions>
        <v-btn variant="text" @click="snackbar.show = false">关闭</v-btn>
      </template>
    </v-snackbar>

  </v-container>
</template>

<script setup>
import {ref, reactive, onMounted} from 'vue';
import ExcelUpload from './ExcelUpload.vue'; // Adjust path
import EvaluationResultsSummary from './EvaluationResultsSummary.vue'; // Adjust path
import EvaluationDetailDialog from './EvaluationDetailDialog.vue'; // Adjust path
import {evaluateDevice, generateSingleReport, generateBatchReports} from '@/services/EvaluationService.js'; // Adjust path
import axios from 'axios'; // For fetching config initially

// --- State ---
const parsedDevices = ref([]); // Data straight from Excel [{ id, name, model, initialValue, bScores }]
const evaluatedDevices = ref([]); // Results after evaluation [{ id, name, ..., evaluation: {...}, error: '...' }]
const isLoading = ref(false);
const evaluationProgress = ref(0); // Progress percentage for batch evaluation

const showDetailDialog = ref(false);
const selectedDeviceForDetail = ref(null);

const snackbar = reactive({
  show: false,
  text: '',
  color: 'info'
});

// --- Config Data (Load once) ---
const secondaryIndicators = ref([]);
const primaryIndicatorWeights = ref({
  '基础检查': 0.2453, // Keep defaults or fetch
  '运行性能': 0.4299,
  '品牌声誉': 0.3248,
}); // Assuming this is stable or fetched

// --- Methods ---
function showSnackbar(text, color = 'info') {
  snackbar.text = text;
  snackbar.color = color;
  snackbar.show = true;
}

function handleParsedData(devices) {
  parsedDevices.value = devices;
  evaluatedDevices.value = []; // Clear previous results
  evaluationProgress.value = 0;
  if (devices.length > 0) {
    showSnackbar(`成功解析 ${devices.length} 台设备。`, 'success');
  } else {
    showSnackbar(`未从文件中解析到有效设备数据。`, 'warning');
  }
}

function handleParseError(errorMessage) {
  parsedDevices.value = [];
  evaluatedDevices.value = [];
  evaluationProgress.value = 0;
  showSnackbar(`文件处理错误: ${errorMessage}`, 'error');
}

async function startBatchEvaluation() {
  if (parsedDevices.value.length === 0) {
    showSnackbar("没有要评估的设备。", 'warning');
    return;
  }

  // Ensure config is loaded before starting
  if (secondaryIndicators.value.length === 0) {
    await fetchEvaluationConfig(); // Make sure config is loaded
    if (secondaryIndicators.value.length === 0) {
      showSnackbar("无法加载评估配置，无法开始评估。", 'error');
      return;
    }
  }


  isLoading.value = true;
  evaluatedDevices.value = []; // Clear previous results before starting
  evaluationProgress.value = 0;
  const results = [];
  const totalDevices = parsedDevices.value.length;

  for (let i = 0; i < totalDevices; i++) {
    const deviceInput = parsedDevices.value[i];
    try {
      // Pass necessary config to the service function
      const result = await evaluateDevice(deviceInput, secondaryIndicators.value, primaryIndicatorWeights.value);
      results.push(result);
    } catch (error) {
      // Error should be handled within evaluateDevice, returning an error object
      results.push({
        ...deviceInput,
        evaluation: null,
        error: `评估调用失败: ${error.message}`
      });
    }
    // Update progress after each device
    evaluationProgress.value = Math.round(((i + 1) / totalDevices) * 100);
    // Update the reactive array incrementally for better UI feedback
    evaluatedDevices.value = [...results];
    // Optional: small delay to allow UI updates if needed

  }

  isLoading.value = false;
  evaluationProgress.value = 100; // Ensure it hits 100
  showSnackbar(`批量评估完成 ${results.length} 台设备。`, 'success');
  // Reset progress slightly after completion for visual clarity
  setTimeout(() => {
    evaluationProgress.value = 0;
  }, 1500);
}

function showDeviceDetails(deviceData) {
  selectedDeviceForDetail.value = deviceData;
  showDetailDialog.value = true;
}

async function handleGenerateBatchReports(selectedDevices) {
  // Ensure config is loaded
  if (secondaryIndicators.value.length === 0) {
    await fetchEvaluationConfig();
    if (secondaryIndicators.value.length === 0) {
      showSnackbar("无法加载评估配置，无法生成报告。", 'error');
      return;
    }
  }
  await generateBatchReports(selectedDevices, secondaryIndicators.value, primaryIndicatorWeights.value);
  showSnackbar(`已开始生成 ${selectedDevices.length} 份报告，请检查您的下载。`, 'success'); // 添加提示
}

async function handleGenerateSingleReport(deviceData) {
  if (secondaryIndicators.value.length === 0) {
    await fetchEvaluationConfig();
    if (secondaryIndicators.value.length === 0) {
      showSnackbar("无法加载评估配置，无法生成报告。", 'error');
      return;
    }
  }
  await generateSingleReport(deviceData, secondaryIndicators.value, primaryIndicatorWeights.value);
  showSnackbar(`报告 "${deviceData.name}-${deviceData.model}" 已生成，请检查您的下载。`, 'success'); // 添加提示
}

// --- Lifecycle / Config Loading ---
async function fetchEvaluationConfig() {
  isLoading.value = true; // Indicate loading config
  try {
    // Fetch secondary indicators if they aren't hardcoded
    // Replace with your actual API endpoint if needed
    const response = await axios.get('/api/secondary-indicators'); // Use the correct endpoint
    secondaryIndicators.value = response.data.secondaryIndicators;

    // Fetch primary weights if needed, otherwise use defaults
    // const weightsResponse = await axios.get('/api/primary-weights');
    // primaryIndicatorWeights.value = weightsResponse.data;

    console.log('评估配置加载成功。');

  } catch (error) {
    console.error('获取评估配置失败:', error);
    showSnackbar('加载评估配置失败，请刷新页面或联系管理员。', 'error');
    // Handle error appropriately, maybe prevent evaluation
    secondaryIndicators.value = []; // Ensure it's empty on failure
  } finally {
    isLoading.value = false; // Finish loading config
  }
}

onMounted(() => {
  fetchEvaluationConfig(); // Load config when component mounts
});

</script>

<style scoped>
/* Add styles for the main page if needed */
</style>